import React, { useState, useEffect, useMemo, memo } from 'react';
import { Spin, Empty, Typography, Card, Descriptions, Table, Collapse, Alert } from 'antd';
import { experimentApi } from '../../services/api';
import { ExperimentFullData } from '../../types';

const { Title, Text } = Typography;

interface InputParametersPanelProps {
  projectNameEn: string;
  experiment: ExperimentFullData | null;
}

interface SnapshotData {
  metadata?: {
    name?: string;
    name_en?: string;
    description?: string;
    time_horizon?: number;
    start_year?: number;
    year_step?: number;
    end_year?: number;
    export_time?: string;
  };
  categories?: Array<{
    name: string;
    name_en: string;
    description?: string;
    parameters: Array<{
      name: string;
      name_en: string;
      param_type: string;
      unit?: string;
      description?: string;
      is_list: boolean;
      is_year_related: boolean;
      values: any[];
    }>;
  }>;
}

// 参数值组件（使用memo优化，移到外部避免重复创建）
const ParameterValue = memo(({ param, metadata }: { param: any; metadata?: any }) => {
  if (!param.values || param.values.length === 0) {
    return <Text type="secondary">无值</Text>;
  }

  if (param.is_list) {
    // 判断是否为年份关联：只检查 is_year_related 字段（支持多种格式）
    const isYearRelated = 
      param.is_year_related === true || 
      param.is_year_related === 'true' || 
      param.is_year_related === 1 ||
      param.is_year_related === '1' ||
      String(param.is_year_related || '').toLowerCase() === 'true';
    
    if (isYearRelated && metadata && metadata.start_year !== undefined) {
      // 年份相关列表 - 第一列显示年份，通过start_year和year_step计算
      const startYear = metadata.start_year || 0;
      const yearStep = metadata.year_step || 1;
      const years = Array.from(
        { length: param.values.length },
        (_, i) => startYear + i * yearStep
      );
      const columns = [
        {
          title: '年份',
          dataIndex: 'year',
          key: 'year',
          width: 100,
        },
        {
          title: '值',
          dataIndex: 'value',
          key: 'value',
          render: (val: any) => (
            <Text>{val !== null && val !== undefined ? String(val) : '-'}</Text>
          ),
        },
      ];
      const dataSource = years.map((year, idx) => ({
        key: year,
        year,
        value: param.values[idx] !== undefined ? param.values[idx] : null,
      }));
      return (
        <Table
          columns={columns}
          dataSource={dataSource}
          pagination={{
            pageSize: 20,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100'],
          }}
          size="small"
          scroll={{ y: 300 }}
        />
      );
    } else {
      // 非年份列表 - 添加分页，使用序号
      const columns = [
        {
          title: '序号',
          dataIndex: 'index',
          key: 'index',
          width: 80,
        },
        {
          title: '值',
          dataIndex: 'value',
          key: 'value',
          render: (val: any) => (
            <Text>{val !== null && val !== undefined ? String(val) : '-'}</Text>
          ),
        },
      ];
      const dataSource = param.values.map((val: any, idx: number) => ({
        key: idx,
        index: idx + 1,
        value: val,
      }));
      return (
        <Table
          columns={columns}
          dataSource={dataSource}
          pagination={{
            pageSize: 20,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100'],
          }}
          size="small"
          scroll={{ y: 300 }}
        />
      );
    }
  } else {
    // 单值 - 不应该到这里，单值在ParameterCard中直接显示
    const value = param.values[0];
    return <Text>{value !== null && value !== undefined ? String(value) : '-'}</Text>;
  }
});

ParameterValue.displayName = 'ParameterValue';

// 参数卡片组件（使用memo优化，移到外部避免重复创建）
const ParameterCard = memo(({ param, metadata }: { param: any; metadata?: any }) => {
  // 单值参数：一行显示
  if (!param.is_list) {
    const value = param.values && param.values.length > 0 
      ? (param.values[0] !== null && param.values[0] !== undefined ? String(param.values[0]) : '-')
      : '无值';
    
    return (
      <div style={{ marginBottom: 12, padding: '12px', background: '#fafafa', borderRadius: '4px' }}>
        <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '8px' }}>
          <Text strong>{param.name}</Text>
          {param.name_en && (
            <Text type="secondary" style={{ fontSize: '12px' }}>
              ({param.name_en})
            </Text>
          )}
          {param.unit && (
            <Text type="secondary" style={{ fontSize: '12px' }}>
              [{param.unit}]
            </Text>
          )}
          <Text style={{ marginLeft: '8px' }}>：</Text>
          <Text>{value}</Text>
          {param.description && (
            <Text type="secondary" style={{ fontSize: '12px', marginLeft: '8px' }}>
              ({param.description})
            </Text>
          )}
        </div>
      </div>
    );
  }

  // 列表参数：直接使用Collapse，自身就是可折叠的
  const headerText = (
    <span>
      <Text strong>{param.name}</Text>
      {param.name_en && (
        <Text type="secondary" style={{ marginLeft: 8 }}>
          ({param.name_en})
        </Text>
      )}
      {param.unit && (
        <Text type="secondary" style={{ marginLeft: 8 }}>
          [{param.unit}]
        </Text>
      )}
      {param.is_year_related && (
        <Text type="secondary" style={{ marginLeft: 8, fontSize: '12px' }}>
          (年份关联)
        </Text>
      )}
      <Text type="secondary" style={{ marginLeft: 8, fontSize: '12px' }}>
        - 共 {param.values?.length || 0} 条
      </Text>
    </span>
  );

  return (
    <div style={{ marginBottom: 12 }}>
      {param.description && (
        <Text type="secondary" style={{ display: 'block', marginBottom: 8, paddingLeft: '12px' }}>
          {param.description}
        </Text>
      )}
      <Collapse
        items={[{
          key: 'list',
          label: headerText,
          children: <ParameterValue param={param} metadata={metadata} />
        }]}
      />
    </div>
  );
});

ParameterCard.displayName = 'ParameterCard';

const InputParametersPanel: React.FC<InputParametersPanelProps> = ({ projectNameEn, experiment }) => {
  const [loading, setLoading] = useState(false);
  const [snapshotData, setSnapshotData] = useState<SnapshotData | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!experiment) {
      setSnapshotData(null);
      setError(null);
      return;
    }

    const loadSnapshot = async () => {
      setLoading(true);
      setError(null);
      try {
        const data = await experimentApi.getExperimentSnapshot(projectNameEn, experiment.id);
        setSnapshotData(data);
      } catch (err: any) {
        console.error('加载快照数据失败:', err);
        setError(err.response?.data?.detail || err.message || '加载输入参数失败');
        setSnapshotData(null);
      } finally {
        setLoading(false);
      }
    };

    loadSnapshot();
  }, [projectNameEn, experiment?.id]);

  if (!experiment) {
    return (
      <div style={{ padding: '20px', textAlign: 'center' }}>
        <Empty description="请先选择一个实验" />
      </div>
    );
  }

  if (loading) {
    return (
      <div style={{ padding: '50px', textAlign: 'center' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ padding: '20px' }}>
        <Alert
          message="加载失败"
          description={error}
          type="error"
          showIcon
        />
      </div>
    );
  }

  if (!snapshotData) {
    return (
      <div style={{ padding: '20px', textAlign: 'center' }}>
        <Empty description="该实验没有输入参数数据" />
      </div>
    );
  }

  const { metadata, categories } = snapshotData;

  return (
    <div style={{ padding: '16px', height: '100%', overflow: 'auto' }}>
      <Title level={4} style={{ marginTop: 0, marginBottom: 16 }}>
        输入参数
      </Title>

      {/* 项目基本信息 */}
      {metadata && (
        <Card style={{ marginBottom: 16 }} size="small">
          <Title level={5} style={{ marginTop: 0, marginBottom: 12 }}>
            项目信息
          </Title>
          <Descriptions column={2} size="small" bordered>
            {metadata.name && (
              <Descriptions.Item label="项目名称">{metadata.name}</Descriptions.Item>
            )}
            {metadata.name_en && (
              <Descriptions.Item label="项目英文名">{metadata.name_en}</Descriptions.Item>
            )}
            {metadata.description && (
              <Descriptions.Item label="描述" span={2}>
                {metadata.description}
              </Descriptions.Item>
            )}
            {metadata.time_horizon !== undefined && (
              <Descriptions.Item label="时间长度">{metadata.time_horizon} 年</Descriptions.Item>
            )}
            {metadata.start_year !== undefined && (
              <Descriptions.Item label="起始年份">{metadata.start_year}</Descriptions.Item>
            )}
            {metadata.year_step !== undefined && (
              <Descriptions.Item label="年份步长">{metadata.year_step}</Descriptions.Item>
            )}
            {metadata.end_year !== undefined && (
              <Descriptions.Item label="结束年份">{metadata.end_year}</Descriptions.Item>
            )}
            {metadata.export_time && (
              <Descriptions.Item label="导出时间" span={2}>
                {new Date(metadata.export_time).toLocaleString('zh-CN')}
              </Descriptions.Item>
            )}
          </Descriptions>
        </Card>
      )}

      {/* 参数分类 - 默认全部折叠，按需展开 */}
      {categories && categories.length > 0 && (
        <Collapse
          items={categories.map((category, catIdx) => ({
            key: String(catIdx),
            label: (
              <span>
                <Text strong>{category.name}</Text>
                {category.name_en && (
                  <Text type="secondary" style={{ marginLeft: 8 }}>
                    ({category.name_en})
                  </Text>
                )}
                {category.parameters && category.parameters.length > 0 && (
                  <Text type="secondary" style={{ marginLeft: 8, fontSize: '12px' }}>
                    ({category.parameters.length} 个参数)
                  </Text>
                )}
              </span>
            ),
            children: (
              <>
                {category.description && (
                  <Text type="secondary" style={{ display: 'block', marginBottom: 12 }}>
                    {category.description}
                  </Text>
                )}
                {category.parameters && category.parameters.length > 0 ? (
                  category.parameters.map((param, paramIdx) => (
                    <ParameterCard key={`${catIdx}-${paramIdx}`} param={param} metadata={metadata} />
                  ))
                ) : (
                  <Empty description="该分类下没有参数" />
                )}
              </>
            ),
          }))}
        />
      )}

      {(!categories || categories.length === 0) && (
        <Empty description="没有参数分类数据" />
      )}
    </div>
  );
};

export default InputParametersPanel;

